<!-- 新增账单 -->
<template>
  <div>
    <el-dialog class="con-dialog" :class="isInfo ? 'margin-top-60' : ''" title="账单" z-index="1000" :fullscreen="isInfo ? true : false" :modal="isInfo ? false : true" :visible.sync="dialogShow" width="90%" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common :filed-list="billList" ref="infoForm" @selectChange="selectChange" :formObj="formObj"></form-common>

      <div class="flex justify-between margin-bottom-15 margin-top-15">
        <span class="font-size-17 font-weight-700">费项信息</span>
        <el-button v-if="!isInfo" type="primary" size="mini" @click="addCost" class="el-button-reset">添加</el-button>
      </div>

      <el-table class="new-table-style bold-scrollbar-table cost-box" :border="true" :data="costList" align="left">
        <el-table-column align="center" label="序号">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="费项名称" width="130">
          <template slot-scope="scope">
            <el-select v-if="chargeType == 'energy'" :disabled="isInfo ? true : false" class="no-border-input yj-input" v-model="scope.row.bizType" clearable>
              <el-option v-for="item in options.billTypeEnergy" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
            <el-select v-else class="no-border-input yj-input" :disabled="isInfo ? true : false" v-model="scope.row.bizType" clearable>
              <el-option v-for="item in options.billTypeNormal" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="计费开始时间" width="145" class-name="no-padding">
          <template slot-scope="scope">
            <el-date-picker class="no-border-input yj-input" v-model="scope.row.cycleStartTime" type="date" value-format="timestamp" clearable placeholder="请选择" @blur="validateDate(scope.row)"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="center" label="计费结束时间" width="145" class-name="no-padding">
          <template slot-scope="scope">
            <el-date-picker class="no-border-input yj-input" v-model="scope.row.cycleEndTime" type="date" value-format="timestamp" clearable placeholder="请选择" @blur="validateDate(scope.row)"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="center" label="应缴费日期" width="145" class-name="no-padding">
          <template slot-scope="scope">
            <el-date-picker class="no-border-input yj-input" v-model="scope.row.paymentDeadline" type="date" value-format="timestamp" clearable placeholder="请选择"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额" min-width="120">
          <template slot-scope="scope">
            <el-input-number :controls="false" class="no-border-input yj-input" v-model="scope.row.amountReceivable" @blur="validateVal(scope.row, 'amountReceivable')"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="不含税金额" min-width="120">
          <template slot-scope="scope">
            <span class="font-size-14">{{ (accSubtr(scope.row.amountReceivable, scope.row.taxAmount) || 0) | twoFix }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="税率" min-width="120">
          <template slot-scope="scope">
            <el-input-number :controls="false" class="no-border-input yj-input" v-model="scope.row.taxRate" @blur="validateVal(scope.row, 'taxRate')"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="税额" min-width="120">
          <template slot-scope="scope">
            <el-input-number :controls="false" class="no-border-input yj-input" v-model="scope.row.taxAmount" @blur="validateVal(scope.row, 'taxAmount')"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column v-if="chargeType == 'energy'" align="center" label="起始读数" min-width="120">
          <template slot-scope="scope">
            <el-input-number :controls="false" class="no-border-input yj-input" v-model="scope.row.startNumber" @blur="astrictEndNum(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column v-if="chargeType == 'energy'" align="center" label="终止读数" min-width="120">
          <template slot-scope="scope">
            <el-input-number :controls="false" class="no-border-input yj-input" v-model="scope.row.endNumber" @blur="astrictEndNum(scope.row)"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column v-if="chargeType == 'energy'" align="center" prop="rate" label="用量" min-width="120">
          <template slot-scope="scope">
            <span class="font-size-14">{{ accSubtr(scope.row.endNumber, scope.row.startNumber) || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="chargeType == 'energy'" align="center" prop="price" label="单价" min-width="120">
          <template slot-scope="scope">
            <span class="font-size-14">{{ accDiv(scope.row.amountReceivable, accSubtr(scope.row.endNumber, scope.row.startNumber) || 0) | twoFix }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="120" v-if="!isInfo">
          <template slot-scope="scope">
            <el-button type="text" class="color-red" @click="deleteFn(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="padding-top-20 padding-bottom-20 font-size-17 font-weight-700">附件信息</div>
      <upload-file v-if="!isInfo" :multiple="false" class="upload-box" :limit="10" tip="" :max-size="100" accept=".xlsx,.xls,.csv,.png,.jpg,.Png,.Jpg,.pdf" :fileList.sync="fileList"> </upload-file>
      <div v-else>
        <template v-if="formObj.attachmentList && formObj.attachmentList.length > 0">
          <el-link class="padding-right-20" type="primary" v-for="item in formObj.attachmentList" :key="item.primaryKey" @click="uploadLoad(item.fileUrl)">{{ item.fileTitle }}</el-link>
        </template>
        <el-empty v-else description="暂无数据"></el-empty>
      </div>

      <div v-if="!isInfo" slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false" class="el-button-reset">取 消</el-button>
        <el-button v-if="type == 'add'" type="primary" @click="confirmFn">提 审</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { apiBillAdd, apiContractByClient, apiAssetList, apiBillInfo } from '../../../api/billManage';
  import formCommon from '@g/components/form/formCommon.vue';
  import { billList } from '../../../assets/form';
  import { guid, setFiledVal, requestTips, askDialog, accSubtr, accDiv, uploadLoad } from '@/common/js/utils';
  import { apiPactConstant, apiCreateAudit } from '@a/index';
  import $ from 'jquery';

  export default {
    props: {
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
      isInfo: {
        type: Boolean,
        default: false,
      },
    },

    data() {
      return {
        accSubtr: accSubtr,
        accDiv: accDiv,
        dialogShow: false,
        billList: billList,
        costList: [],
        type: 'add',
        formObj: { attachmentList: [] },
        assetList: [],
        fileList: [],
        chargeType: '', //收款单类型
        userInfo: JSON.parse(localStorage.getItem('userInfo')),
        projectKey: localStorage.getItem('projectKey'),
        uploadLoad: uploadLoad,
      };
    },

    watch: {
      options: {
        deep: true,
        handler(val) {
          this.setSelectOptions();
        },
      },
    },

    methods: {
      //添加时初始化
      async init() {
        this.dialogShow = true;
        this.costList = [];
        if (this.isInfo) {
          this.initDomSetting();
          this.banForm();
          this.getInfo();
        } else {
          this.$nextTick(() => {
            this.$refs.infoForm.initModel();
          });
        }
      },

      //详情
      async getInfo() {
        let res = await apiBillInfo({ workId: this.$route.query.processWorkId });
        this.getContractList(res.customerKey);
        this.getChargeItemList(res.contractCode);
        this.chargeType = res.chargeType;
        this.formObj = res;
        this.costList = res.billList;
        setTimeout(() => {
          $('.yj-input').css('pointer-events', 'none');
        }, 500);
      },

      //保存
      async confirmFn() {
        if (this.costList.length == 0) {
          this.$message.warning('账单为空！！');
          return;
        }

        let costFiledList = []; //费项明细
        let model = this.$refs.infoForm.validateForm(); //基本信息
        if (!model) return;

        if (this.costList.length == 0) {
          this.$message.warning('请添加费项明细!');
          return;
        }

        let validateMustCost = this.validateMustCost();
        if (!validateMustCost) {
          this.$message.warning('请检查费项信息的必填项！！');
          return;
        }

        askDialog('确认提交？', async () => {
          this.costList.forEach(item => {
            item.projectKey = this.projectKey;
          });
          model.billList = this.costList;

          let attachmentList = [];
          this.fileList.forEach(item => {
            attachmentList.push({ fileTitle: item.name, fileUrl: item.response.data.rows[0].sourceUrl, fileId: item.response.data.rows[0].key });
          });

          model.attachmentList = attachmentList;

          let res = await apiBillAdd(model);
          if (res.success) {
            this.submitFn(res.key);
          } else {
            this.$message.error(res.message);
          }
        });
      },

      //提审
      async submitFn(key) {
        let param = {
          businessKey: key,
          userPrimaryKey: this.userInfo.key,
          projectKey: this.projectKey,
          type: '账单新建',
          typeKey: 'billCreate',
        };
        let res = await apiCreateAudit(param);
        requestTips(res, () => {
          this.dialogShow = false;
          this.$emit('confirmAddBill');
        });
      },

      //添加费项明细
      addCost() {
        this.costList.push({});
      },

      deleteFn(index) {
        askDialog('确认删除？', async () => {
          this.costList.splice(index, 1);
        });
      },

      //表单事件
      selectChange(data) {
        if (data.filedName == 'customerKey') {
          this.getContractList(data.filedVal);
          data.cb('contractCode', '');
          data.cb('assetCode', '');
        }
        if (data.filedName == 'contractCode') {
          data.cb('assetCode', '');
          let contractKey = this.getContractKey(data.filedVal);
          data.cb('contractKey', contractKey);
          this.getChargeItemList(data.filedVal);
        }
        if (data.filedName == 'assetCode') {
          if (data.filedVal) {
            let assetObj = this.getAssetName(data.filedVal);
            if (!assetObj) return;
            data.cb('assetName', assetObj.assetName);
            data.cb('assetKey', assetObj.primaryKey);
          }
        }
        if (data.filedName == 'chargeType') {
          this.chargeType = data.filedVal || '';
          this.costList = [];
        }
      },

      //合同
      async getContractList(customerKey) {
        let res = await apiContractByClient({
          partnerKey: customerKey,
        });
        this.contractList = res.rows || [];
        this.billList.forEach(ele => {
          if (ele.bindFieldName == 'contractCode') {
            ele.optionList = res.rows || [];
          }
        });
      },

      //赋值下拉框数据源
      setSelectOptions() {
        this.billList.forEach(ele => {
          if (ele.bindFieldName == 'customerKey') {
            ele.optionList = this.options.clientList || [];
          }
          if (ele.bindFieldName == 'chargeType') {
            ele.optionList = this.options.gatherTypeList || [];
          }
        });
      },

      //资产 事项 assetType 空的代表是事项 不为空代表是资产
      async getChargeItemList(contractCode) {
        let assetList = [];
        let res = await apiAssetList({ contractCode: contractCode, status: 2 });
        res.rows.forEach(item => {
          if (item.assetType) {
            assetList.push(item);
          }
        });
        this.assetList = assetList;
        this.billList.forEach(ele => {
          if (ele.bindFieldName == 'assetCode') {
            ele.optionList = assetList || [];
          }
        });
      },

      getContractKey(code) {
        let target = this.contractList.find(item => item.contractCode == code);
        return target ? target.primaryKey : '';
      },

      getAssetName(assetCode) {
        let target = this.assetList.find(item => item.assetCode == assetCode);
        return target ? target : false;
      },

      //校验合同费用约定的必填
      validateMustCost() {
        for (let i = 0, len = $('.cost-box').find('.el-input__inner').length; i < len; i++) {
          let item = $('.cost-box').find('.el-input__inner')[i];
          if ($(item).val() == '') {
            $(item).css('border', '1px solid red');
            return false;
          } else {
            $(item).css('border', 'none');
          }
        }
        return true;
      },

      //校验输入的内容 收款单类型是减免的情况下，只能输入负数
      validateVal(row, filedName) {
        if (this.chargeType == 'discount') {
          if (row[filedName] > 0) {
            row[filedName] = -row[filedName];
          }
        } else {
          if (row[filedName] < 0) {
            row[filedName] = -row[filedName];
          }
        }
      },

      //校验时间
      validateDate(row) {
        if (row.cycleStartTime > row.cycleEndTime) {
          row.cycleEndTime = '';
          this.$message.warning('结束时间应大于开始时间！');
        }
      },

      //限制终止读数
      astrictEndNum(row) {
        row.endNumber = row.endNumber < row.startNumber ? row.startNumber : row.endNumber;
      },

      //详情时初始化dom
      initDomSetting() {
        $('.con-dialog .el-dialog__header').hide();
      },

      //禁止form必填 可输入
      banForm() {
        this.billList.forEach(item => {
          item.isRequired = false;
          item.isDisabled = true;
        });
      },
    },

    components: { formCommon },
  };
</script>
<style lang="scss" scoped>
  .delete-btn {
    position: absolute;
    top: -7px;
    right: 0;
  }
  ::v-deep .el-button--text {
    font-size: 18px;
  }
  ::v-deep .no-padding {
    padding: 0 !important;

    .cell {
      padding: 0 !important;
    }
  }
  ::v-deep .el-form-item__label {
    padding: 0;
  }
  .cost-box {
    ::v-deep .el-input.is-disabled .el-input__inner {
      background-color: #fff;
      border-color: #fff;
      color: #333;
      font-size: 16px;
    }
  }
</style>
